<template>
  <view class="container">
    <view class="header">
      <image :src="$image('/storeminiapp/login_header_bg.png')"></image>
    </view>
    <view class="login-form">
      <u-form :model="form" ref="uForm">
        <u-form-item left-icon="account" prop="username">
          <u-input v-model="form.username" placeholder="请输入账号" />
        </u-form-item>
        <u-form-item left-icon="lock" prop="password">
          <u-input type="password" v-model="form.password" placeholder="请输入密码" />
        </u-form-item>
      </u-form>
      <u-button type="primary" :customStyle="customStyle" :loading="loading" @click="submit">登录</u-button>
    </view>
  </view>
</template>

<script>
import store from '@/store'
import tool from '@/utils/tool'
import storage from '@/utils/storage'
import { ACCESS_TOKEN, Login_USER, LOGIN_COUNTER, SELECT_PICKUP_ID } from "@/store/mutation-types"
import * as StoreApi from '@/api/store'
import * as SettingApi from "@/api/setting"
import * as UserApi from '@/api/user'
import WebSocketIM from '@/utils/webSocketIM'
import * as PickApi from '@/api/order/pick'

export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          {
            required: true,
            message: "账号必填不能为空",
            trigger: ["change", "blur"]
          }
        ],
        password: [
          {
            required: true,
            min: 6,
            message: "密码不能小于6位数",
            trigger: ["change", "blur"]
          }
        ]
      },
      loading: false,
      customStyle: { marginTop: '32px', height: '100rpx' }
    }
  },
  computed: {
    loginInfo() {
      return store.getters.loginInfo
    },
    userInfo() {
      return store.getters.userInfo
    },
    store() {
      return store.getters.store
    }
  },
  onShow() {
    const { username, password } = storage.get(Login_USER)
    if (username && password) {
      this.form = {
        username,
        password
      }
    }
    // 只要进入login页面就清除token
    store.commit('SET_TOKEN', storage.set(ACCESS_TOKEN, ''))
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.loading = true
          store.dispatch('Login', {
            username: this.form.username,
            password: tool.aesEncrypt(this.form.password),
            randomStr: Date.parse(new Date()),
          })
            .then(() => {
              storage.set(Login_USER, { username: this.form.username, password: this.form.password })
              store.dispatch('UserInfo').then(() => {
                this.getPageData()
              })
            })
            .catch(() => {
              this.loading = false
            })
            .finally(() => {})
        }
      })
    },
    async getPageData() {
      const { tenantId } = this.loginInfo
      const { shopId } = this.userInfo
      // 获取商户列表
      const { data: tenants } = await StoreApi.getTenantsList()
      if (!tenants?.length) {
        this.$toast('该账号下无可用商户，请联系管理员')
        store.dispatch('Logout', false)
        this.loading = false
        return
      }
      store.commit('SET_TENANTS', tenants)
      const tenant = tenants.find(item => item.id == tenantId) || tenants[0] || {}
      store.commit('SET_TENANT', tenant)
      // 2.获取门店列表
      const { data: shops } = await StoreApi.getShopsList(tenant.id)
      if (!shops?.length) {
        this.$toast('该账号下无可用门店，请联系管理员')
        store.dispatch('Logout', false)
        this.loading = false
        return
      }
      store.commit('SET_SHOPS', shops)
      const shop = shops.find(item => item.id === shopId) || shops[0] || {}
      store.commit('SET_STORE', shop)
      store.commit('SET_BUSINESS_TYPE', shop.id === '0' ? 0 : 1)
      if (shop?.shopOnlineChannels) {
        const channels = shop.shopOnlineChannels.map(item => {
          return {
            thirdChannelId: item.thirdChannelId,
            channelName: item.thirdChannelName
          }
        })
        store.commit('SET_CHANNELS', channels)
      }
      // 3.获取指定店铺
      const loginCounter = storage.get(LOGIN_COUNTER)
      const { data: stores } = await StoreApi.getStoresList(shop.id)
      const counter = stores.find(item => item.storeId === loginCounter)
      if (counter) {
        store.commit('SET_COUNTER', counter)
        store.commit('SET_BUSINESS_TYPE', 2)
      } else if (!shop?.isFullControl && stores.length) {
        store.commit('SET_COUNTER', stores[0])
        store.commit('SET_BUSINESS_TYPE', 2)
        storage.set(LOGIN_COUNTER, stores[0].storeId)
      }
      // 4.获取自提点列表
      try {
        const { data: pickups } = await StoreApi.getPickupList(shop.id)
        store.commit('SET_PICKUPS', pickups)
        const selectPickupId = storage.get(shop.id + SELECT_PICKUP_ID)
        const pickup = pickups.find(item => item.pickupId === selectPickupId)
        if (pickup) {
          store.commit('SET_PICKUP', pickup)
        }
      } catch (e) { }
      // 5.获取用户菜单
      try {
        const { data: menus } = await UserApi.userMenus()
        menus && store.commit('SET_MENUS', menus)
      } catch (e) { }
      // 获取拣货员状态
      try {
        PickApi.getPickUser().then(({ data }) => {
          data && store.commit('SET_PICKER_STATUS', data)
        }).catch(() => {})
      } catch (e) { }
      this.loading = false
      const path = this.$checkModule('ly_tab_home') ? 'home' : 'order'
      this.$navTo(`pages/${path}/index`)
      const { data: allChannels } = await SettingApi.getChannelList()
      allChannels && store.commit('SET_ALL_CHANNELS', allChannels)
      const imWSInstance = new WebSocketIM()
      getApp().globalData.imWSInstance = imWSInstance
      imWSInstance.connect(false)
    }
  }
}
</script>

<style>
page {
  background: #ffffff;
}
</style>

<style scoped lang="scss">
.container {

  .header {
    height: 564rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .login-form {
    position: absolute;
    width: 100%;
    top: 550rpx;
    background: #fff;
    padding: 50rpx 48rpx;
    border-radius: 20rpx 20rpx 0 0;
  }
}
</style>
